//
//  UserInfoManager.m
//  MobaoInteraction
//
//  Created by a on 2019/12/26.
//  Copyright © 2019 mobao. All rights reserved.
//

#import "UserInfoManager.h"

//用户信息存储路径
#define MYUserPath [NSString stringWithFormat:@"%@/Documents/MYUser2.txt",NSHomeDirectory()]

static UserInfoManager *instance = nil;
@interface UserInfoManager(){
    
}
@end
@implementation UserInfoManager
+ (UserInfoManager *)sharedManager {
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        instance = [[UserInfoManager alloc] init];
    });
    return instance;
}
-(id)init{
    self = [super init];
    if (self) {
        NSDictionary *dic = [self getDataWithPath:MYUserPath];
        DLog(@"user===%@",dic);
        if (dic.allKeys.count>0) {
            [self analyzeUserInfoWith:dic];
        }else{
            [self initEmptyData];
        }
    }
    return self;
}

-(void)initData{
    self.isLogin = NO;
    self.iToken = @"";

    self.bindPhone = @"";
    self.phone = @"";
    self.vip_expiry_date = @"";
}

//保存数据
-(void)saveDataWithDict:(NSDictionary *)dict  withPath:(NSString *)path{
    if (dict == nil) {
        return;
    }
    NSData *resultData= [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSFileManager *fm=[NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        [fm createFileAtPath:path contents:nil attributes:nil];
    }
    [resultData writeToFile:path atomically:YES];
}

//得到数据
-(NSDictionary *)getDataWithPath:(NSString *)path{
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dict;
    if (data) {
        dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:nil];
    }else{
        dict = [[NSDictionary alloc] init];
    }
    return dict;
}

-(void)initEmptyData {
    self.isLogin = NO;
    self.iToken = @"";
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"iToken"];
    [self saveDataWithDict:@{} withPath:MYUserPath];
    [UIApplication sharedApplication].applicationIconBadgeNumber  = 0;
}

- (void)analyzeUserIToken:(NSString *)token{
    //self.iToken = dict[@"data"][@"iToken"];
    self.iToken = token;
    [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"iToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self getUserInfoData:^(BOOL flag) {
        
    }];
}

- (void)setIToken:(NSString *)iToken{
    _iToken = iToken;
    [[NSUserDefaults standardUserDefaults] setValue:_iToken forKey:@"iToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)analyzeUserInfoWith:(NSDictionary *)dict {
    self.isLogin = YES;
    self.bindPhone = dict[@"bindPhone"];
    self.phone = dict[@"phone"];
    self.vip_expiry_date = dict[@"expiresDate"];
}

- (void)getUserInfoData:(void (^)(BOOL flag))success{
    self.iToken = [[NSUserDefaults standardUserDefaults] valueForKey:@"iToken"];
    DLog(@"self.iToken==%@",self.iToken);
    if (self.iToken.length > 0) {
        [[HttpHelper sharedInstance] sendGet:@"api/user/first" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
            if (responseObject.code == 1) {
                [self saveDataWithDict:responseObject.data[@"data"] withPath:MYUserPath];
                [self analyzeUserInfoWith:responseObject.data[@"data"]];
                if(success){
                    success(YES);
                }
            }else{
                if(success){
                    success(NO);
                }
            }
        } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
            
        }];
    }else{
        [self initEmptyData];
    }
}

-(void)userInit{
    DLog(@"注册");
    //    if (!selectDic) {
    //        return;
    //    }
    DLog(@"uuid===%@",[Helper getOnlyStr]);
    [[HttpHelper sharedInstance] sendPost:@"api/visitor/login" parameters:@{@"uuid":[Helper getOnlyStr]} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        if (responseObject.code == 1) {
            [UserInfoManager sharedManager].iToken = responseObject.data[@"data"][@"token"];
            [self getUserInfoData:^(BOOL flag) {
                
            }];
        }
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}

- (BOOL)isVip{
    if(self.vip_expiry_date == nil  || self.vip_expiry_date.length < 2){
        return NO;
    }
    if([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:self.vip_expiry_date]){
        return YES;
    }
    return NO;
}

@end
